package com.lin.consumer;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class Demo2Consumer {
    private static String QUEUE_NAME;

    @Value("${queue.demo2_queue_name}")
    public void  setQueueName(String queueName) {
        QUEUE_NAME = queueName;
    }

    public static void work(Integer id) throws Exception {
        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        System.out.println("Worker"+id+" start to waiting for work!");

        DeliverCallback deliverCallback = (consumerTag,delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("worker"+id+" receive work："+message);
            Integer time = Integer.parseInt(message.substring(4));
            for(int i=0;i<time;i++) {
                System.out.println("worker"+id+" work in " + (i+1) + "second...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("worker"+id+" finish work and send ack");
            //发送一个ack信号
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
        };
//      这里第二个参数设置成true可以自动回复ack
//        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumeTag->{});
        channel.basicConsume(QUEUE_NAME,false,deliverCallback,consumeTag->{});
    }
}
